<#systemSituation globalInfo="${globalInfo}"/>
<link rel="stylesheet" href="/static/css/metroStyle.css">
<!-- 防止页面数据重复定义,模板数据统一在此 -->
<!--:
    var ableList = dicttag.getDictList('yes_no');
    var ableJson = commontag.toJson(ableList);
    var isAdmin = usertag.isAdmin();
-->

<!-- widget grid with search -->
<section>

    <!-- row -->
    <div class="row">

        <!-- NEW WIDGET START -->
        <article class="col-xs-12 col-sm-12 col-md-12 col-lg-12">

            <div class="jarviswidget jarviswidget-color-blueDark" data-widget-editbutton="false">
                <header>
                    <span class="widget-icon"> <i class="fa fa-table"></i> </span>

                    <h2>角色列表 </h2>

                </header>

                <div>

                    <!-- widget edit box -->
                    <div class="jarviswidget-editbox">
                        <!-- This area used as dropdown edit box -->
                    </div>
                    <!-- end widget edit box -->

                    <!-- widget content -->
                    <div class="widget-body no-padding">
                        <div id="roleTable"></div>
                    </div>

                </div>
            </div>

        </article>
        <!-- WIDGET END -->
    </div>
    <!-- end row -->
</section>
<!-- end widget grid with search -->

<!-- menu tree -->
<div id="role-menu-tree"></div>
<!-- end menu tree -->

<!-- assign role user -->
<div id="assign-role-user" class="well dialog-well" style="display: none;">
    <!-- widget content -->
    <div class="alert alert-block alert-success">
        <h4 class="alert-heading user-assign"><i class="fa fa-check-square-o"></i>!</h4>
        <p>
            通过双向选择器为角色分配用户.
        </p>
    </div>
    <div class="inbox-body no-content-padding">
        <div class="inbox-side-bar bordered">
            <div id="assignOfficeTree" class="ztree">
                tree
            </div>
        </div>
        <div class="table-wrap custom-scroll animated fast fadeInRight">
            <select multiple="multiple" id="assignDuallistbox">
            </select>
        </div>

    </div>
    <!-- end widget content -->
</div>
<!-- end assign role user -->

<!-- role form content -->
<div class="well dialog-well" id="role-dialog" style="display: none;">

    <div class="widget-body no-padding">

        <form id="role-form" action="${ctx}/sys/role/save" method="post" class="smart-form">

            <fieldset>
                <div class="hide">
                    <input type="hidden" name="id"> 　
                </div>
                <div class="row">
                    <section class="col col-6">
                        <label class="label">角色名称</label>
                        <label class="input">
                            <i class="icon-append fa fa-key"></i>
                            <input name="oldName" type="hidden">
                            <input type="text" name="name" placeholder="角色的名称">
                            <b class="tooltip tooltip-bottom-right">角色的名称,必须设置</b>
                        </label>
                    </section>
                    <section class="col col-6">
                        <label class="label">英文名称</label>
                        <label class="input">
                            <i class="icon-append fa fa-globe"></i>
                            <input name="oldEnname" type="hidden">
                            <input type="text" name="enname" placeholder="角色的英文名称">
                            <b class="tooltip tooltip-bottom-right">角色的英文名称,工作流用户组标识</b>
                        </label>
                    </section>
                </div>

                <section>
                    <label class="label">角色类型</label>
                    <label class="select" rel="tooltip" data-placement="bottom"
                           data-original-title="工作流组用户组类型（任务分配：assignment、管理角色：security-role、普通角色：user）">
                        <select name="type">
                            <option value="assignment">任务分配员</option>
                            <option value="security-role">管理角色</option>
                            <option value="user">普通角色</option>
                        </select><i></i>
                    </label>
                </section>

                <div class="row">
                    <section class="col col-6">
                        <label class="label">是否系统数据</label>
                        <label class="select" rel="tooltip" data-placement="bottom"
                               data-original-title='“是”代表此数据只有超级管理员能进行修改，“否”则表示拥有角色修改人员的权限都能进行修改'>
                            <select name="sysData">
                                <!--:
                                    for(able in ableList!){
                                -->
                                <option value="${able.value!''}">${able.label!''}</option>
                                <!--:
                                    }
                                -->
                            </select><i></i>
                        </label>
                    </section>
                    <section class="col col-6">
                        <label class="label">是否可用</label>
                        <label class="select" rel="tooltip" data-placement="bottom"
                               data-original-title='“是”代表此数据可用，“否”则表示此数据不可用'>
                            <select name="useable">
                                <!--:
                                    for(able in ableList!){
                                -->
                                <option value="${able.value!''}">${able.label!''}</option>
                                <!--:
                                    }
                                -->
                            </select><i></i>
                        </label>
                    </section>
                </div>

                <section>
                    <label class="label">备注信息</label>
                    <label class="textarea">
                        <i class="icon-append fa fa-comment"></i>
                        <textarea rows="4" name="remarks"></textarea>
                    </label>
                </section>
            </fieldset>

        </form>

    </div>
</div>
<!-- end role form content -->


<script type="text/javascript">

    /* DO NOT REMOVE : GLOBAL FUNCTIONS!
     *
     * pageSetUp(); WILL CALL THE FOLLOWING FUNCTIONS
     *
     * // activate tooltips
     * $("[rel=tooltip]").tooltip();
     *
     * // activate popovers
     * $("[rel=popover]").popover();
     *
     * // activate popovers with hover states
     * $("[rel=popover-hover]").popover({ trigger: "hover" });
     *
     * // activate inline charts
     * runAllCharts();
     *
     * // setup widgets
     * setup_widgets_desktop();
     *
     * // run form elements
     * runAllForms();
     *
     ********************************
     *
     * pageSetUp() is needed whenever you load a page.
     * It initializes and checks for all basic elements of the page
     * and makes rendering easier.
     *
     */
    pageSetUp();

    /*
     * ALL PAGE RELATED SCRIPTS CAN GO BELOW HERE
     */
    // PAGE RELATED SCRIPTS
    // pagefunction
    var pagefunction = function () {

        var params = {};
        var $roleFrom = $("#role-form");
        $roleFrom.validate({
            // Rules for form validation
            rules: {
                // 为了不污染html代码,验证统一在js中
                name: {
                    required: true,
                    maxlength: 50,
                    remote: {
                        url: "${ctx}/sys/role/checkName",
                        type: "post",
                        data: {
                            'oldName': function () {
                                return $roleFrom.find('input[name=oldName]').val();
                            },
                            'name': function () {
                                return $roleFrom.find('input[name=name]').val();
                            }
                        }
                    }
                },
                enname: {
                    required: true,
                    maxlength: 50,
                    remote: {
                        url: "${ctx}/sys/role/checkEnname",
                        type: "post",
                        data: {
                            'oldEnname': function () {
                                return $roleFrom.find('input[name=oldEnname]').val();
                            },
                            'enname': function () {
                                return $roleFrom.find('input[name=enname]').val();
                            }
                        }
                    }
                },
                remarks: {
                    maxlength: 250
                }
            },

            // Messages for form validation,use default
            messages: {
                // 不覆盖使用默认js多语言文件
                name: {remote: "角色名已存在"},
                enname: {remote: "英文名已存在"}
            },
            submitHandler: function (form) {
                // 遮罩
                var loadIndex = parent.layer.load(0, {shade: 0.4});

                $(form).ajaxSubmit({
                    dataType: "json",
                    success: function (data) {
                        parent.layer.close(loadIndex);

                        if (data && data.status == 'success') {
                            // .dt-toolbar .dt_refresh .dt-refresh-btn
                            parent.$('#roleTable .dt-toolbar .dt-refresh-btn').trigger('click');
                            parent.messageBox(data.message, "success");
                        } else {
                            parent.messageBox(data.message, "error");
                        }
                        // 显示
                        parent.layer.closeAll('page');
                    },
                    error: function () {
                        parent.layer.close(loadIndex);
                        parent.messageBox("修改角色错误!", "error");
                    }
                });
                // always return false to prevent standard browser submit and page navigation
                return false;
            },
            // Do not change code below
            errorPlacement: function (error, element) {
                error.insertAfter(element.parent());
            }
        });

        /**
         * 根据类型获取类型label
         * @param value 类型value
         */
        function getLabel(value) {
            var dicts = eval('${ableJson!""}');
            // 设置默认显示type
            var label = value;
            if (dicts) {
                $.each(dicts, function (i, dict) {
                    if (dict['value'] == value) {
                        label = dict['label'];
                        return false;
                    }
                });
            }
            return label;
        }

        var datatable = new DataTableData({
                    databind: $('#roleTable').get(0),
                    //数据请求url地址
                    dataurl: '${ctx}/sys/role/list',
                    //数据请求参数
                    params: params,
                    hasCache: true,
                    hasCheck: true,
                    info: false,
                    checkBind: 'id',
                    toolbarStates: {
                        "add": {
                            action: function () {
                                form();
                            }
                        },
                        "edit": {
                            action: function () {
                                var selDatas = datatable.getSelectedDatas();
                                if (selDatas && selDatas.length > 0) {
                                    form(selDatas[0]);
                                }
                            }
                        },
                        "delete": {
                            mult: false,   // 不允许多选删除
                            action: function () {
                                var selDatas = datatable.getSelectedDatas();
                                if (selDatas && selDatas.length > 0) {
                                    var id = selDatas[0]['id'];
                                    layer.confirm('您真的要删除选择的数据？', {
                                                icon: 3,
                                                title: '删除角色',
                                                btn: ['确定', '取消'], //按钮
                                                shade: 0.4 //不显示遮罩
                                            }, function (index) {
                                                // send
                                                ajaxCoomand({
                                                    url: '${ctx}/sys/role/delete',
                                                    data: {id: id},
                                                    callback: function () {
                                                        datatable.refresh();
                                                    }
                                                });

                                                layer.close(index);
                                            }
                                    );
                                }
                            }
                        }
                    },
                    columns: [
                        {data: 'name', title: '角色名称'},
                        {data: 'enname', title: '英文名'},
                        {
                            data: 'type',
                            title: '类型',
                            render: function (data) {
                                if (data == "assignment") {
                                    return "任务分配员";
                                } else if (data == "security-role") {
                                    return "管理角色";
                                } else {
                                    return "普通角色";
                                }
                            }
                        },
                        {
                            data: 'sysData', title: '是否系统数据',
                            render: function (value) {
                                return '<div class="text-center"><span class="label label-default">' + getLabel(value) + '</span></div>';
                            }
                        },
                        {
                            data: 'useable', title: '是否可用',
                            render: function (value) {
                                return '<div class="text-center"><span class="label label-primary">' + getLabel(value) + '</span></div>';
                            }
                        },
                        {
                            data: 'id',
                            title: '操作',
                            render: function (data) {
                                return '<a href="javascript:" class="btn btn-warning" style="padding: 0 5px;" onclick="assign(' + "'" + data + "'" + ')"><i class="fa fa-user-plus"></i> 分配用户</a>' +
                                        '<span class="margin-right-5 margin-left-5"></span>' +
                                        '<a href="javascript:" class="btn btn-success" style="padding: 0 5px;" onclick="auth(' + "'" + data + "'" + ')"><i class="fa fa-magic"></i> 授权</a>';
                            }
                        }
                    ]
                }
        );

        /**
         * 打开编辑框
         */
        function form(role) {
            var opr = '添加';
            if (role != null && !$.isEmptyObject(role) && role['id'] != null) {
                opr = "修改";
            }
            // 添加修改对话框
            layer.open({
                type: 1,
                title: opr + '角色',
                shadeClose: false,
                shade: 0.4,
                area: ['720px'],   //高度自动适应
                maxmin: true,
                content: $('#role-dialog'),
                btn: ['确定', '取消'],
                success: function () {
                    // 当你需要在层创建完毕时即执行一些语句，可以通过该回调。success会携带两个参数，分别是当前层DOM当前层索引
                    // 这里可以通过发送ajax获取,也可通过表格选择时获取的行的值设置
                    if (role != null && !$.isEmptyObject(role)) {
                        if (role['id'] != null) {
                            $roleFrom.find('input[name=id]').val(role['id']);
                        }
                        $roleFrom.find('input[name=name]').val(role['name']);
                        $roleFrom.find('input[name=enname]').val(role['enname']);
                        $roleFrom.find('input[name=oldName]').val(role['name']);
                        $roleFrom.find('input[name=oldEnname]').val(role['enname']);
                        $roleFrom.find('select[name=type]').val(role['type']);
                        $roleFrom.find('select[name=sysData]').val(role['sysData']);
                        $roleFrom.find('select[name=useable]').val(role['useable']);
                        $roleFrom.find('textarea[name=remarks]').val(role['remarks']);
                    }
                },
                end: function () {
                    // 无论是确认还是取消，只要层被销毁了，end都会执行，不携带任何参数
                    $roleFrom.find('input[name=id]').val('');
                    $roleFrom.find('input[name=name]').val('');
                    $roleFrom.find('input[name=enname]').val('');
                    $roleFrom.find('input[name=oldName]').val('');
                    $roleFrom.find('input[name=oldEnname]').val('');
                    $roleFrom.find('select[name=type]').get(0).selectedIndex = 0;
                    $roleFrom.find('select[name=sysData]').get(0).selectedIndex = 0;
                    $roleFrom.find('select[name=useable]').get(0).selectedIndex = 0;
                    $roleFrom.find('textarea[name=remarks]').val('');
                },
                yes: function () { //或者使用btn1
                    // 按钮【确定】的回调
                    $roleFrom.submit();
                },
                cancel: function (index) { //或者使用btn2
                    // 按钮【取消】的回调
                    layer.close(index);
                }
            });
        }

        /**
         * 分配用户按钮点击
         */
        function assign(id) {
            // 设置属性
            // 添加修改对话框
            layer.open({
                type: 1,
                title: "分配用户",
                shadeClose: false,
                shade: 0.4,
                area: ['840px'],   //高度自动适应
                maxmin: true,
                content: $('#assign-role-user'),
                btn: ['确定', '取消'],
                success: function () {
                    // 设置角色信息
                    var role = null;
                    var datas = datatable.getTableData();
                    $.each(datas, function (index, value) {
                        if (value != null && value['id'] == id) {
                            role = value;
                            return true;
                        }
                    });
                    if (role != null) {
                        $('#assign-role-user').find('.user-assign').html("<i class='fa fa-check-square-o'></i> 角色名: " + role['name'] + "");
                    }
                    // 获取当前角色下的用户列表
                    $.ajax({
                        url: '${ctx}/sys/role/roleUsers',
                        data: {id: id},
                        type: 'post',
                        async: false,
                        dataType: 'json',
                        success: function (data) {
                            if (data && data.length > 0) {
                                // 点击展示下属用户
                                $.each(data, function (index, val) {
                                    $('#assignDuallistbox').append('<option value="' + val['id'] + '" selected>' +
                                            val['loginName'] + ' [' + val['name'] + '] </option>');
                                });
                                $('#assignDuallistbox').bootstrapDualListbox('refresh');

                            }
                        }
                    });
                    // 发送请求，取得office的数据
                    $.ajax({
                        url: '${ctx}/sys/office/treeData',
                        type: 'post',
                        // json格式要求严格验证
                        dataType: "json",
                        success: function (result) {
                            build(result);
                        },
                        error: function (xhr, error) {
                            console.info('tree load data error.' + error);
                        }
                    });
                },
                end: function () {
                    // 清除左右菜单
                    $('#assignDuallistbox').find('option').remove();
                    $('#assignDuallistbox').bootstrapDualListbox('refresh');
                },
                yes: function (index) { //或者使用btn1
                    // 按钮【确定】的回调
                    var selIds = $('#assignDuallistbox').val();
                    ajaxCoomand({
                        url: '${ctx}/sys/role/assign',
                        data: {id: id, userIds: selIds}
                    });
                    layer.close(index);
                },
                cancel: function (index) { //或者使用btn2
                    // 按钮【取消】的回调
                    layer.close(index);
                }
            });
        }


        /**
         * 构造树
         */
        function build(zNodes) {
            // tree params
            var setting = {
                view: {
                    selectedMulti: false, dblClickExpand: false,
                    nameIsHTML: true,
                    showIcon: false,
                    showTitle: false
                },
                check: {
                    enable: false
                },
                // {id, pId, name}
                data: {simpleData: {enable: true}},
                callback: {
                    onClick: function (event, treeId, treeNode) {
                        // 获取当前节点下的用户列表
                        $.ajax({
                            url: '${ctx}/sys/role/officeUsers',
                            data: {officeId: treeNode.id},
                            type: 'post',
                            async: false,
                            dataType: 'json',
                            success: function (data) {
                                // remove old.
                                var $assignDuallistbox = $('#assignDuallistbox');
                                var selIds = $assignDuallistbox.val();
                                var $ops = $assignDuallistbox.find('option');
                                if (selIds && selIds.length > 0) {
                                    $.each($ops, function (index, value) {
                                        if (selIds.indexOf($(value).val()) < 0) {
                                            $(value).remove();
                                        }
                                    });
                                } else {
                                    $ops.remove();
                                }

                                $assignDuallistbox.bootstrapDualListbox('refresh');
                                if (data && data.length > 0) {
                                    // 点击展示下属用户
                                    $.each(data, function (index, val) {
                                        if (selIds && selIds.length > 0) {
                                            // 去除已经选择的
                                            if (selIds.indexOf(val['id']) < 0) {
                                                $assignDuallistbox.append('<option value="' + val['id'] + '">' +
                                                        val['loginName'] + ' [' + val['name'] + '] </option>');
                                            }
                                        } else {
                                            $assignDuallistbox.append('<option value="' + val['id'] + '">' +
                                                    val['loginName'] + ' [' + val['name'] + '] </option>');
                                        }
                                    });
                                    $assignDuallistbox.bootstrapDualListbox('refresh');

                                }
                            }
                        });
                    }
                }
            };
            // 初始化树结构
            var officeTree = $.fn.zTree.init($("#assignOfficeTree"), setting, zNodes);

            // 默认展开一级节点
            var nodes = officeTree.getNodesByParam("level", 0);
            for (var i = 0; i < nodes.length; i++) {
                officeTree.expandNode(nodes[i], true, false, false);
            }
            // 默认选中根节点
            var node = officeTree.getNodeByParam("id", "1");
            if (node) {
                officeTree.selectNode(node);
                $("#" + node.tId + "_a").click();
            }
        }

        /*
         * BOOTSTRAP DUALLIST BOX
         */
        loadScript("/static/js/plugin/bootstrap-duallistbox/jquery.bootstrap-duallistbox.js", initDuallistbox);
        // 初始化角色->用户配置选中组件
        function initDuallistbox() {
            $('#assignDuallistbox').bootstrapDualListbox({
                nonSelectedListLabel: '未分配用户',
                selectedListLabel: '已分配用户',
                preserveSelectionOnMove: '移动',
                filterPlaceHolder: '过滤',
                filterTextClear: '显示所有',
                infoTextEmpty: '无用户',
                infoText: '总共有 {0}',
                moveSelectedLabel: '移动选择项',
                moveAllLabel: '移动所有',
                removeSelectedLabel: '删除选择项',
                removeAllLabel: '删除所有',
                moveOnSelect: false,
                selectorMinimalHeight: '270',
                nonSelectedFilter: ''
            });
        }

        /**
         * 初始化一个tree selecter, 之后通过refresh设置值
         */
        var $tree = $('#role-menu-tree');
        var menuTreeSelect = new TreeSelecter({
            databind: $tree.get(0),
            title: '菜单',
            name: 'parent.id',
            // 隐藏域值
            value: '0',
            // 输入框名称
            labelName: 'parent.name',
            chkStyle: 'checkbox',
            // 输入框值
            labelValue: '',
            // 数据请求url地址,树结构数据地址
            dataurl: '${ctx}/sys/menu/treeData',
            // 根据当前用户是否是admin角色决定
            allowClear: false,
            callback: function (selected, dataself) {
                // 保存
                ajaxCoomand({
                    url: '${ctx}/sys/role/saveMenuIds',
                    data: {id: dataself, menuIds: selected},
                    callback: function () {
                    }
                });
            }
        });
        $tree.find('.form-tree-info').hide();

        /**
         * 授权按钮点击
         */
        function auth(id) {
            // 获取当前role的所有选中菜单
            $.ajax({
                url: '${ctx}/sys/role/menuIds',
                data: {id: id},
                type: 'post',
                async: false,
                success: function (data) {
                    // 设置属性
                    menuTreeSelect.refresh({
                        value: data,
                        labelValue: '',
                        dataself: id
                    });
                }
            });
            $tree.find('input[name="parent.name"]').trigger('click');
        }

        // 注册
        window.assign = assign;
        window.auth = auth;

    };

    // destroy generated instances
    // pagedestroy is called automatically before loading a new page
    // only usable in AJAX version!
    var pagedestroy = function () {
        // 移除注册方法
        window.assign = undefined;
        window.auth = undefined;

        $('#assignDuallistbox').bootstrapDualListbox('destroy');
    };
    // end destroy

    // load related plugins
    loadScript("/static/js/plugin/jquery-tree/jquery.ztree.all-3.5.js", function () {
        loadScript("/static/js/plugin/jquery-tree/jquery.ztree.exhide-3.5.js", function () {
            loadScript("/static/js/extend/TreeSelecter.js", function () {
                loadScript("/static/js/plugin/datatables/jquery.dataTables.js", function () {
                    loadScript("/static/js/plugin/datatables/dataTables.colVis.js", function () {
                        loadScript("/static/js/plugin/datatables/dataTables.tableTools.js", function () {
                            loadScript("/static/js/plugin/datatables/dataTables.bootstrap.js", function () {
                                loadScript("/static/js/plugin/datatable-responsive/datatables.responsive.js", function () {
                                    loadScript("/static/js/plugin/jquery-form/jquery.form.js");
                                    loadScript("/static/js/extend/DataTableData.js", pagefunction);
                                });
                            });
                        });
                    });
                });
            });
        });
    });

</script>